package cn.fxxk.modular.system.scheduling;

import cn.fxxk.common.Constants;
import cn.fxxk.modular.system.entity.FxxkAccesstoken;
import cn.fxxk.modular.system.mapper.FxxkAccesstokenMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@EnableScheduling
public class FxxkAccesstokenTask {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private FxxkAccesstokenMapper fxxkAccesstokenMapper;

    /**
     * 获取corpAccessToken
     */
    @Async
    @Scheduled(initialDelay=1000, fixedDelay = 7200000)
    public void getToken() {
        System.out.println("执行getToken");
        String getTokenUrl = Constants.GET_TOKEN;
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        //设置content-type
        MediaType type = MediaType.parseMediaType("application/json");
        headers.setContentType(type);
        //设置请求体
        Map<String, Object> params = new HashMap<>();
        params.put("appId", Constants.APP_ID);
        params.put("appSecret", Constants.APP_SECRET);
        params.put("permanentCode", Constants.PERMANENT_CODE);

        //用HttpEntity封装整个请求报文
        HttpEntity<Map<String, Object>> files = new HttpEntity<>(params, headers);

        //服务端返回的json格式："
        String result = restTemplate.postForObject(getTokenUrl, files, String.class);

        Map<String, Object> mapTypes = JSONObject.parseObject(result);
        if("success".equals((String)mapTypes.get("errorMessage"))){
            FxxkAccesstoken fxxkAccesstoken =  FxxkAccesstoken.builder()
                    .id(1)
                    .corpAccessToken((String)mapTypes.get("corpAccessToken"))
                    .corpId((String)mapTypes.get("corpId"))
                    .expiresIn((int)mapTypes.get("expiresIn"))
                    .createTime(new Date())
                    .build();
            fxxkAccesstokenMapper.updateById(fxxkAccesstoken);
        }else{
            log.error("corpAccessToken获取失败");
        }
        System.out.println(mapTypes);
    }

    /**
     * 获取CODE
     */
    //@Async
    //@Scheduled(initialDelay=1000, fixedDelay = 7200000)
    public void getCode() {
        System.out.println("执行getCode");
        String getCodeUrl = Constants.GET_CODE;
        System.out.println("执行getCode的url="+getCodeUrl);
        httpURLConectionGET(getCodeUrl);
    }
    /**
     * 获取refreshToken
     */
    //@Async
    //@Scheduled(initialDelay=1000, fixedDelay = 7200000)
    public void refreshToken() {
        System.out.println("执行refreshToken");
        String getRefreshToken = Constants.GET_REFRESH_TOKEN;
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        //设置content-type
        MediaType type = MediaType.parseMediaType("application/json");
        headers.setContentType(type);
        //设置请求体
        Map<String, Object> params = new HashMap<>();
        params.put("appId", Constants.APP_ID);
        params.put("appSecret", Constants.APP_SECRET);
        params.put("grantType", "refresh_token");
        params.put("redirectUrl", "https://open.fxiaoke.com/xxx");

        //用HttpEntity封装整个请求报文
        HttpEntity<Map<String, Object>> files = new HttpEntity<>(params, headers);

        //服务端返回的json格式："
        String result = restTemplate.postForObject(getRefreshToken, files, String.class);

        Map<String, Object> mapTypes = JSONObject.parseObject(result);
        System.out.println(mapTypes);
    }

    /**
     * 接口调用 GET
     */
    public void httpURLConectionGET(String getUrl) {
        try {
            HttpGet httpGet = new HttpGet(getUrl);
            HttpClients.createDefault().execute(httpGet);
        } catch (Exception e) {
            System.out.println("失败!");
        }
    }
}
